package com.neulogistics.contrib.procuredcenter.infrastructure.persistence.converter;

import cn.hutool.json.JSONUtil;
import com.neulogistics.contrib.procuredcenter.domain.model.aggregate.PurchaseOrder;
import com.neulogistics.contrib.procuredcenter.domain.model.enumeration.PurchaseType;
import com.neulogistics.contrib.procuredcenter.domain.model.valueobject.PurchaseItem;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.po.PurchaseOrderPO;
import org.springframework.beans.BeanUtils;

public class PurchaseOrderEntityPOConverter {
    private static final int Rate = 100;

    public static PurchaseOrderPO entityToPO(PurchaseOrder purchaseOrder){
        if(purchaseOrder == null)
            return null;

        PurchaseOrderPO purchaseOrderPO = new PurchaseOrderPO();
        // 复制普通属性
        BeanUtils.copyProperties(purchaseOrder, purchaseOrderPO);

        if(purchaseOrder.getPurchaseType() != null){
            // 枚举值转换
            purchaseOrderPO.setPurchaseType(purchaseOrder.getPurchaseType().id);
        }
        if(purchaseOrder.getPurchaseItem() != null){
            // json对象转换
            purchaseOrderPO.setPurchaseItem(JSONUtil.parseObj(purchaseOrder.getPurchaseItem()));
        }
        if(purchaseOrder.getPurchaseTotal() != null){
            // 价格转换
            purchaseOrderPO.setPurchaseTotal((int) (purchaseOrder.getPurchaseTotal() * Rate));
        }
        return purchaseOrderPO;
    }

    public static PurchaseOrder POToEntity(PurchaseOrderPO purchaseOrderPO){
        if(purchaseOrderPO == null)
            return null;

        PurchaseOrder purchaseOrder = new PurchaseOrder();
        // 复制普通属性
        BeanUtils.copyProperties(purchaseOrderPO, purchaseOrder);
        // 枚举值转换
        purchaseOrder.setPurchaseType(PurchaseType.fromValue(purchaseOrderPO.getPurchaseType(), PurchaseType.class));
        // json对象转换
        purchaseOrder.setPurchaseItem(JSONUtil.toBean(purchaseOrderPO.getPurchaseItem(), PurchaseItem.class));
        // 价格转换
        purchaseOrder.setPurchaseTotal(Double.valueOf(purchaseOrderPO.getPurchaseTotal()) / Rate);
        return purchaseOrder;
    }
}
